﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.Serialization;
using WebGioiThieu.Models;
using WebGioiThieu.Modules.SlideImages;

namespace WebGioiThieu.Controllers
{
    public class HomeController : Controller
    {
        private IntroductionWebDBEntities db = new IntroductionWebDBEntities();

        public ActionResult About()
        {
            return View();
        }

        [ChildActionOnly]
        public PartialViewResult GetSlideImages()
        {
            //get
            string path = Server.MapPath("~/Configs/SlideImages.xml");
            var deserializer = new XmlSerializer(typeof(SlideImages));
            var textReader = new StreamReader(path);
            var model = (SlideImages)deserializer.Deserialize(textReader);
            textReader.Close();

            model.SlideImageList = model.SlideImageList.OrderBy(c => c.DisplayOrder).ToList();
            return PartialView(model);
        }
        public ActionResult Index(string criteria, int page = 1)
        {
            int total;
            var persons = string.IsNullOrEmpty(criteria)
                                ? Get(page, out total)
                                : Get(page, criteria, out total);

            ViewData["page"] = page;
            ViewData["total"] = total;
            ViewData["criteria"] = criteria;



            return View(persons);
        }

        public ActionResult GetTour(string criteria, int page)
        {
            int total;

            var persons = string.IsNullOrEmpty(criteria)
                                ? Get(page, out total)
                                : Get(page, criteria, out total);

            ViewData["page"] = page;
            ViewData["total"] = total;
            ViewData["criteria"] = criteria;

            return PartialView("_TourList", persons);
        }


        /*các phương thức repository phân trang (viết tạm ở đây)
        ---------------------------------*/
        public IList<Tour> Get(int page, out int total)
        {
            var tour = db.Tours.ToList().OrderBy(i => i.NgayCapNhat).Skip((page - 1) * 6).Take(6);
            var totalTour = db.Tours.ToList().Count();
            total = totalTour / 6 + (totalTour % 6 > 0 ? 1 : 0);
            return tour.ToList();
        }

        public IList<Tour> Get(int page, string criteria, out int total)// lấy theo tiêu chí tìm kiếm criteria
        {
            var tour = db.Tours.Where(i => i.TieuDe.Contains(criteria)).OrderBy(i => i.TieuDe).Skip((page - 1) * 6).Take(6);
            var totalTour = tour.ToList().Count();
            total = totalTour / 6 + (totalTour % 6 > 0 ? 1 : 0);
            return tour.ToList();
        }
    }
}
